var cpt = 0;
var commentPolyline;

// Google Map
var map;

// Trajet
var trajet = [];
trajet.push(new google.maps.LatLng("50.61265", "3.1414"));
trajet.push(new google.maps.LatLng("50.61264", "3.14079"));
trajet.push(new google.maps.LatLng("50.61264", "3.14079"));
trajet.push(new google.maps.LatLng("50.6124", "3.14083"));
trajet.push(new google.maps.LatLng("50.61212", "3.14067"));
trajet.push(new google.maps.LatLng("50.61205", "3.14098"));
trajet.push(new google.maps.LatLng("50.612", "3.14107"));
trajet.push(new google.maps.LatLng("50.61195", "3.14108"));
trajet.push(new google.maps.LatLng("50.61187", "3.14138"));
trajet.push(new google.maps.LatLng("50.61156", "3.14166"));
trajet.push(new google.maps.LatLng("50.61134", "3.14153"));
trajet.push(new google.maps.LatLng("50.61124", "3.14129"));
trajet.push(new google.maps.LatLng("50.61101", "3.14132"));

// test des commentaires
var temp = [];
var comment = [];

// commentaires deja defini
var test = [];
test.push(new google.maps.LatLng("50.61264", "3.14079"));
test.push(new google.maps.LatLng("50.6124", "3.14083"));
test.push(new google.maps.LatLng("50.61212", "3.14067"));

var test1 = [];
test1.push(new google.maps.LatLng("50.6124", "3.14083"));
test1.push(new google.maps.LatLng("50.61212", "3.14067"));

var test2 = [];
test2.push(new google.maps.LatLng("50.61156", "3.14166"));
test2.push(new google.maps.LatLng("50.61134", "3.14153"));
test2.push(new google.maps.LatLng("50.61124", "3.14129"));

var testPolyline = new google.maps.Polyline({
	path : test,
	clickable : true,
	strokeWeight : 6,
	strokeColor : "#FF0000",
	zIndex : 3
});

var testPolyline2 = new google.maps.Polyline({
	path : test1,
	clickable : true,
	strokeWeight : 2,
	strokeColor : "#0000FF",
	zIndex : 4
});

var testPolyline3 = new google.maps.Polyline({
	path : test2,
	clickable : true,
	strokeWeight : 6,
	strokeColor : "#FF8000",
	zIndex : 3
});

// directions options
var optionsDirections = {
	draggable : true,
	polylineOptions : {
		strokeColor : '#f42418'
	}
};

// par dÃ©faut "Villeneuve d'ascq, campus"
var defaultLat = 50.61212752432054;
var defaultLng = 3.1416231393814087;

// initialise google map
function initialize() {
	// Enable the visual refresh
	google.maps.visualRefresh = true;

	// options de google maps
	var mapOptions = {
		disableDoubleClickZoom : true,
		// centre de la map
		center : {
			lat : defaultLat,
			lng : defaultLng
		},
		// suppression des panneaux de control de google map
		panControl : false,
		streetViewControl : false,
		mapTypeControl : false,
		// reglage du zoom
		zoom : 17,
		maxZoom : 19,
		minZoom : 16,
		preserveViewport : true
	};

	map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

	google.maps.event.addListener(map, 'zoom_changed', function() {
		drawDefaultRoad(trajet);
	});

	google.maps.event.addListener(map, 'mousemove', function(event) {
		// survol de la map avec la souris
		var distance_min = 100;
		aroundMouse(event, testPolyline, distance_min);
		aroundMouse(event, testPolyline2, distance_min);
		aroundMouse(event, testPolyline3, distance_min);
	});

	drawDefaultRoad(trajet);
}

// parcours l'ensemble des points et regarde s'il est proche des coordonnées de
// la souris
function aroundMouse(event, polyline, distance_min) {
	polyline.setMap(null);
	for (var i = 0; i < polyline.getPath().getArray().length; i++) {
		if (distance(event.latLng.k, event.latLng.D, polyline.getPath()
				.getArray()[i].k, polyline.getPath().getArray()[i].D, "K") * 1000 < distance_min) {
			polyline.setMap(map);
			break;
		}
	}
}

// fonction de dessin
// location.k = lat
// location.D = lng
function drawComment(location) {
	// on ajoute les coordonnees dans une array
	directionsDisplay = new google.maps.DirectionsRenderer(optionsDirections);
	comment.push(new google.maps.LatLng(location.k, location.D));
	// On dessine petit Ã petit notre trajet
	if (comment.length > 1) {
		commentPolyline = new google.maps.Polyline({
			path : comment,
			clickable : true,
			strokeWeight : 6,
			strokeColor : "#746DFF",
			zIndex : 2
		});
		commentPolyline.setMap(map);
		var service = new google.maps.DirectionsService(), commentPolyline, snap_path1 = [];
		// fontion qui va reformer le chemin en suivant parfaitement la route
		for (j = 0; j < comment.length - 1; j++) {
			service.route({
				origin : comment[j],
				destination : comment[j + 1],
				travelMode : google.maps.DirectionsTravelMode.BICYCLING
			}, function(result, status) {
				if (status == google.maps.DirectionsStatus.OK) {
					snap_path1 = snap_path1
							.concat(result.routes[0].overview_path);
					commentPolyline.setPath(snap_path1);
				} else
					alert("Directions request failed: " + status);
			});
		}
	}
}


// affiche ou cache les commentaires
function displayComment() {
	testPolyline.setMap(map);
	testPolyline2.setMap(map);
	testPolyline3.setMap(map);
}

function eraseComment() {
	testPolyline.setMap(null);
	testPolyline2.setMap(null);
	testPolyline3.setMap(null);
}


// desactive ou reactive les commentaires
function disable() {
	$("#my_comment").prop('disabled', true);
	$("#send_button").addClass('disabled');
}

function enable() {
	$("#my_comment").prop('disabled', false);
	$("#send_button").removeClass('disabled');
}

// refresh la map
function reloadMap() {
	google.maps.event.trigger(map, 'resize');
}

// calcul de distance entre 2 longitudes et latitudes
// Rien = Miles
// K = Kilometres
// N = Nautical Miles
function distance(lat1, lon1, lat2, lon2, unit) {
	var radlat1 = Math.PI * lat1 / 180
	var radlat2 = Math.PI * lat2 / 180
	var radlon1 = Math.PI * lon1 / 180
	var radlon2 = Math.PI * lon2 / 180
	var theta = lon1 - lon2
	var radtheta = Math.PI * theta / 180
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1)
			* Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist)
	dist = dist * 180 / Math.PI
	dist = dist * 60 * 1.1515
	if (unit == "K") {
		dist = dist * 1.609344
	}
	if (unit == "N") {
		dist = dist * 0.8684
	}
	return dist;
}

// chemin par defaut
function drawDefaultRoad(trajet) {
	var trajetPolyline = new google.maps.Polyline({
		path : trajet,
		clickable : true,
		strokeWeight : 6,
		strokeColor : "green",
		zIndex : 1
	});

	var service = new google.maps.DirectionsService(), trajetPolyline, snap_path1 = [];

	trajetPolyline.setMap(map);
	google.maps.event
			.addListener(
					trajetPolyline,
					'dblclick',
					function(event) {
						switch (cpt) {
						case 0:
							$("#help")
									.html(
											"Etape 2 : Double cliquez, ensuite, pour ajouter le point d'arrivé de votre commentaire");
							drawComment(event.latLng);
							cpt++;
							break;
						case 1:
							$("#help")
									.html(
											"Etape 3 : Insérez votre commentaire dans le champs (vous pouvez encore le modifier)");
							drawComment(event.latLng);
							enable();
							cpt++;
							break;
						default:
							// drawComment(event.latLng);
							break;
						}
					});
}

google.maps.event.addDomListener(window, 'load', initialize);
